package ucd.csi.comp30220.fall2011.oteop.flight.impl;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import ucd.csi.comp30220.fall2011.oteop.flight.FlightStatus;

public class FlightStatusPublisher {
    
    public static final String BROADCAST_ADDRESS = "224.1.1.1";
    public static final int BROADCAST_PORT = 41024;
    
    private InetAddress address;
    private int port;
    private MulticastSocket socket;
        
    public FlightStatusPublisher() throws Exception {
        address = InetAddress.getByName(FlightStatusPublisher.BROADCAST_ADDRESS);
        port = FlightStatusPublisher.BROADCAST_PORT;
        socket = new MulticastSocket();
    }
    
    public void publish(FlightStatus status) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(status);
        oos.close();
        byte[] data = baos.toByteArray();
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        socket.send(packet);
    }
}
